import React, { useState, useEffect } from 'react';
import { Input, message } from 'antd';
import { SafetyCertificateOutlined } from '@ant-design/icons';
import { getCaptcha } from '@/services/ant-design-pro/api';
import uuid from '@/pkg/uuid/uuid';

interface CaptchaInputValue {
  captchaCode?: string;
  captchaKey?: string;
}

interface CaptchaInputProps {
  value?: CaptchaInputValue;
  onChange?: (value: CaptchaInputValue) => void;
}

const CaptchaInput: React.FC<CaptchaInputProps> = ({ value = {}, onChange }) => {
  const [captchaCode, setCaptchaCode] = useState<string>('');
  const [captchaKey, setCaptchaKey] = useState<string>('');
  const [imageData, setImageData] = useState<string>('');

  // 触发改变
  const triggerChange = (changedValue: { captchaCode?: string; captchaKey?: string }) => {
    if (onChange) {
      onChange({ captchaCode, captchaKey, ...value, ...changedValue });
    }
  };
  /**
   * 获取验证码
   */
  const handleGetCaptcha = async () => {
    const uniqueId = uuid.generateTimestampUUID();

    try {
      // 获取验证码
      const msg = await getCaptcha({ uuid: uniqueId });
      console.log({ msg });
      if (msg.no === '0') {
        setCaptchaKey(uniqueId);
        setImageData(msg.captcha || '');
        console.log(msg.captcha);
        triggerChange({ captchaKey: uniqueId });
        return;
      }
      message.error('获取验证码失败!');
    } catch (error) {
      const defaultLoginFailureMessage = '获取验证码失败！';
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };

  useEffect(() => {
    handleGetCaptcha();
  }, []);

  // 输入框变化
  const onChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    const code = e.target.value || '';
    setCaptchaCode(code);
    triggerChange({ captchaCode: code });
  };

  // 时间类型变化
  const onClickImage = () => {
    handleGetCaptcha();
  };

  return (
    <span>
      <Input.Group compact>
        <Input
          prefix={<SafetyCertificateOutlined style={{ color: '#319cff' }} />}
          placeholder="请输入验证码"
          onChange={onChangeInput}
          style={{
            width: '75%',
            marginRight: 5,
            padding: '6.5px 11px 6.5px 11px',
            verticalAlign: 'middle',
          }}
        />
        <img
          style={{
            width: '23%',
            height: '35px',
            verticalAlign: 'middle',
            padding: '0px 0px 0px 0px',
          }}
          src={imageData}
          onClick={onClickImage}
        />
      </Input.Group>
    </span>
  );
};
export default CaptchaInput;
